<template>
	<div class="tag-wrap" :class="{ 'tags-view-container': tagList.length > 0 }">
		<router-link
			ref="el"
			class="tag"
			v-for="item in tagList"
			:to="{ path: item.path }"
			:class="{ active: isActive(item) }"
			:key="item.path"
			@contextmenu.prevent="openMenu(item, $event)"
		>
			<el-icon v-show="isActive(item)"><SwitchButton /></el-icon>
			{{ item.title }}
			<el-icon v-show="item.path != '/index'" @click.prevent.stop="delSelectTag(item)"><Close /></el-icon>
		</router-link>
	</div>
	<!-- 弹出右键菜单 -->
	<ul v-show="isVisibleMenu" :style="{ left: menuPoint.left + 'px', top: menuPoint.top + 'px' }" class="contextmenu">
		<li @click="refreshSelectedTag">取消菜单</li>
		<li @click="closeOthersTags">关闭其他</li>
		<li @click="closeAllTags()">全部关闭</li>
	</ul>
</template>

<script setup lang="ts">
import { ref, computed, watch, reactive } from 'vue'
import { useTagStore } from '@/stores/modules/tagview'
import { useRouter, useRoute } from 'vue-router'
import { Close, SwitchButton } from '@element-plus/icons-vue'
import { ITagView } from '@/api/interface'
const tagStore = useTagStore()
const router = useRouter()
const route = useRoute()
const isVisibleMenu = ref<boolean>(false) //控制右键菜单
//右键菜单坐标
const menuPoint = reactive<{ top: number; left: number }>({
	top: 0,
	left: 0
})
const selectedTag = ref<ITagView>() // 选中标签
/**
 * 动态获取标签数组
 */
const tagList = computed(() => tagStore.tagList)
/**
 * 侦听路由切换，
 * 动态添加标签导航
 */
watch(route, () => {
	tagStore.addTag(route)
})
/**
 * 点击弹框其它区域隐藏弹框
 * 实现原理: 侦听弹框显示，添加页面点击事件，绑定关闭菜单事件，
 */
watch(isVisibleMenu, value => {
	if (value) {
		document.body.addEventListener('click', closeMenu)
	} else {
		document.body.removeEventListener('click', closeMenu)
	}
})
/**
 * 判断当前路由
 * @param item
 */
const isActive = (item: ITagView) => item.path == route.path
/**
 * 删除单个标签
 *  - 删除激活标签，将最后一个标签设置为当前激活标签
 *  - 最后标签为首页直接切换到首页
 * @param route
 */
const delSelectTag = (route: ITagView) => {
	tagStore.deleteTag(route)
	if (isActive(route)) {
		const lastRoute = tagStore.tagList.slice(-1)[0] // 查找数组中最后一个元素
		// 最后一个为首页标签直接路由切换首页
		if (lastRoute.path == '/index') {
			router.push({ path: '/index' })
		} else {
			router.push(lastRoute)
		}
	}
}
/**
 * 打开右键菜单
 * @param tag
 * @param e
 */
const openMenu = (tag: ITagView, e: any) => {
	menuPoint.left = e.clientX
	menuPoint.top = e.clientY
	selectedTag.value = tag
	isVisibleMenu.value = true
}
/**
 * 关闭所有标签
 */
const closeAllTags = () => {
	tagStore.deleteAllTag()
	closeMenu()
}
/**
 * 关闭其它标签
 */
const closeOthersTags = () => {
	tagStore.deleteOtherTag(selectedTag.value as ITagView)
	closeMenu()
}
/**
 * 取消弹框
 */
const refreshSelectedTag = () => {
	closeMenu()
}
/**
 * 隐藏右键弹框
 */
const closeMenu = () => {
	isVisibleMenu.value = false
}
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
